package com.toplion.project.tools.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

/**
 * @author azhao
 */
public class ConsumerStringOutStream extends OutputStream {

    private final Consumer<String> consumer;

    public ConsumerStringOutStream(Consumer<String> consumer) {
        this.consumer = consumer;
    }

    public static final char LINE_SEPARATOR = '\n';

    private final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    @Override
    public void write(final int i) {
        byte b = (byte) i;
        if ((char) b == LINE_SEPARATOR) {
            flush();
            return;
        }
        baos.write(b);
    }

    @Override
    public void flush() {
        String str = new String(baos.toByteArray(), StandardCharsets.UTF_8);
        consumer.accept(str);
        baos.reset();
    }

    @Override
    public void close() {
        try {
            baos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
